<?php

declare (strict_types=1);

namespace app\beautiful\controller\cashier;

use app\BaseController;
use app\beautiful\helper\payment\PaymentMicropayHelper;
use app\beautiful\logic\LogsLogic;
use app\beautiful\logic\MemberWalletLogic;
use app\beautiful\logic\order\OrderCashierLogic;
use app\beautiful\logic\PartnerLogic;
use app\beautiful\logic\printer\PrinterLogic;
use app\beautiful\model\appointment\CommissionModel;
use app\beautiful\model\appointment\CPModel;
use app\beautiful\model\appointment\TechnicianMeritsModel;
use app\beautiful\model\appointment\TechnicianModel;
use app\beautiful\model\mall\GoodsModel;
use app\beautiful\model\mall\GoodsSkuModel;
use app\beautiful\model\member\MemberCouponModel;
use app\beautiful\model\member\MemberModel;
use app\beautiful\model\member\MemberOnceCardItemModel;
use app\beautiful\model\member\MemberOnceCardModel;
use app\beautiful\model\member\MemberProjectModel;
use app\beautiful\model\member\MemberSnapUpModel;
use app\beautiful\model\order\CashierOrderItemModel;
use app\beautiful\model\order\CashierOrderModel;
use app\beautiful\model\order\CashierOrderProjectModel;
use app\common\logic\DataLogic;
use app\common\model\ShopAlPaymentModel;
use pay\Alipay;
use think\facade\Db;

class Order extends BaseController
{
    public function getOrderList()
    {
        $member_id = $this->request->param('member_id/d', 0);
        $where = [
            ['shop_id', '=', $this->request->shopId],
            ['is_delete', '=', 0],
        ];

        if (!empty($order_id)) $where[] = ['order_id', '=', $order_id];
        if ($member_id != 0) $where[] = ['member_id', '=', $member_id];
        if (!empty($order_type)) $where[] = ['order_type', '=', $order_type];
        if (!empty($status)) $where[] = ['status', '=', $status];

        $order_model = new CashierOrderModel();
        $order_model = $order_model->with(['skus', 'member']);

        $order = ['add_time' => 'desc'];
        $field = "*";
        $append = ['add_time_format', 'pay_time_format', 'status_means', 'pay_type_mean'];
        $return = DataLogic::getDataList($order_model, $where, $order, $field, $this->request->limit, $this->request->page, $append);

        return $this->success($return);
    }

    public function getOrderDetail()
    {
        $order_id = $this->request->param('order_id/d', 0);
        if ($order_id == 0) return $this->error('订单不存在#1');
        if (null === $order = CashierOrderModel::find($order_id)) return $this->error('订单不存在#2');
        if ($order->shop_id != $this->request->shopId) return $this->error('订单不存在#3');
        if ($order->is_delete != 0) return $this->error('订单不存在#4');

        $member = MemberModel::find($order->member_id);

        $items = CashierOrderItemModel::where([
            ['shop_id', '=', $this->request->shopId],
            ['order_id', '=', $order_id]
        ])->select()->toArray();
        $projrcts = CashierOrderProjectModel::where([
            ['shop_id', '=', $this->request->shopId],
            ['order_id', '=', $order_id]
        ])->select()->toArray();


        $order->append(['add_time_format', 'pay_time_format', 'status_means', 'pay_type_mean']);

        $detail = [
            'order_id' => $order->order_id,
            'add_time_format' => $order->add_time_format,
            'status' => $order->status,
            'status_means' => $order->status_means,
            'need_pay' => $order->need_pay,
            'pay_type' => $order->pay_type,
            'pay_type_mean' => $order->pay_type_mean,
            'pay_time_format' => $order->pay_time_format,
            'total_price' => $order->total_price,
            'youhui_balance' => $order->youhui_price,
            'coupon_money' => $order->coupon_money,
            'member' => $member,
            'member_name' => $member === null ? '-' : $member->nick_name,
            'member_mobile' => $member === null ? '-' : $member->mobile,
            'items' => $items,
            'projrcts' => $projrcts,
            'balance' => $order->balance,
            'cash' => $order->cash,
        ];

        return $this->success(['detail' => $detail]);
    }

    public function createOrder()
    {
        $member_id = $this->request->param('member_id/d', 0);
        $total_price = $this->request->param('total_price/f', 0);
        $coupon_id = $this->request->param('coupon_id/d', 0);
        $youhui_price = $this->request->param('youhui_price/f', 0);

        $goods = $this->request->param('goods', []);
        $goods = json_decode($goods, true);
        $projects = $this->request->param('projects');
        $projects = json_decode($projects, true);
        $params = [
            'member_id' => $member_id,
            'total_price' => $total_price,
            'coupon_id' => $coupon_id,
            'youhui_price' => $youhui_price,
            'goods' => $goods,
            'projects' => $projects,
        ];
        Db::startTrans();
        try {

            $order_cashier_logic = new OrderCashierLogic($this->request->shopId);
            $order_id = $order_cashier_logic->createOrder($params);

            Db::commit();
            return $this->success(['order_id' => $order_id]);
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    protected $merits = [];
    protected $write_off_error = [];

    public function write_off($projects)
    {
        if ($projects['type'] == 0) return;
        if ($projects['type'] == 1 && null != $member_snap_up = MemberSnapUpModel::find($projects['member_snap_up_id'])) {
            $member_project = MemberProjectModel::where([
                ['member_id', '=', $member_snap_up->member_id],
                ['source', '=', 'snap_up'],
                ['project_id', '=', $member_snap_up->project_id],
                ['member_snap_up_id', '=', $projects['member_snap_up_id']],
                ['total_num', '=', $member_snap_up->total_num],
                ['remain_num', '=', $member_snap_up->remain_num]
            ])->find();
            if ($member_project == null) {
                $this->write_off_error[] = [
                    "info" => $projects,
                    "error" => 'MemberProjectModel is null'
                ];
                return;
            }
            $num = 1;
            $remain_num = $member_snap_up->remain_num - $num;


            //处理我的抢购
            $member_snap_up->remain_num = $remain_num;
            if ($remain_num <= 0) $member_snap_up->status = 8;
            $member_snap_up->save();
            //处理我的项目
            $member_project->remain_num = $remain_num;
            $member_project->save();

            //添加核销记录
            $res = LogsLogic::project($this->request->shopId, $member_snap_up->member_id, 'snap_up', $projects['member_snap_up_id'], $num, $remain_num, '', 1, $this->request->staffId);
            //打印机
            $printer_logic = new PrinterLogic($this->request->shopId);
            $printer_logic->print('snapUpOrderWriteOff', $res);

        } elseif ($projects['type'] == 2 && null != $member_once_card_item = MemberOnceCardItemModel::find($projects['member_once_card_item_id'])) {
            if (null == $member_once_card = MemberOnceCardModel::find($member_once_card_item->member_once_card_id)) return;
            $member_project = MemberProjectModel::where([
                ['member_id', '=', $member_once_card_item->member_id],
                ['source', '=', 'once_card'],
                ['project_id', '=', $member_once_card_item->project_id],
                ['member_once_card_item_id', '=', $projects['member_once_card_item_id']],
                ['total_num', '=', $member_once_card_item->total_num],
                ['remain_num', '=', $member_once_card_item->remain_num]
            ])->find();
            if ($member_project == null) return;
            $num = 1;
            $remain_num = $member_once_card_item->remain_num - $num;

            //处理我的次卡项目
            $member_once_card_item->remain_num = $remain_num;
            $member_once_card_item->save();

            //处理次卡状态
            if (null === MemberOnceCardItemModel::where([
                    ['shop_id', '=', $this->request->shopId],
                    ['member_id', '=', $member_once_card_item->member_id],
                    ['member_once_card_id', '=', $member_once_card->member_once_card_id],
                    ['remain_num', '>', 0]
                ])->find()) {
                $member_once_card->status = 8;
                $member_once_card->save();
            }
            //处理我的项目
            $member_project->remain_num = $remain_num;
            $member_project->save();

            //添加核销记录
            $res = LogsLogic::project($this->request->shopId, $member_once_card_item->member_id, 'once_card', $projects['member_once_card_item_id'], $num, $remain_num, '', 1, $this->request->staffId);
            $printer_logic = new PrinterLogic($this->request->shopId);
            $printer_logic->print('onceCardOrderWriteOff', $res);
        }

    }

    public function technicianMerits($order_project)
    {
        if ($order_project['technicians'] == '' || $order_project['technicians'] == null) return;
        $ids = explode(',', $order_project['technicians']);
        foreach ($ids as $id) {
            $technician_info = TechnicianModel::find($id);
            if ($technician_info != null && $technician_info['commission_id'] != 0) {
                $cp = CPModel::where([
                    ['commission_id', '=', $technician_info['commission_id']],
                    ['project_id', '=', $order_project['project_id']],
                ])
                    ->find();
                if (null == $cp || count($cp->toArray()) == 0) continue;
                $money = 0;
                switch ($cp['type']) {
                    case 0:
                        $money = round((float)$cp['value'] * (float)$order_project['market_price'], 2);
                        break;
                    case 1:
                        $money = (float)$cp['value'];
                        break;
                    case 2:
                        $money = round((float)$cp['value'] * (float)$order_project['original_price'], 2);
                        break;
                }

                $this->merits[] = [
                    'technician_id' => $id,
                    'shop_id' => $this->request->shopId,
                    'project_id' => $order_project['project_id'],
                    'order_project_id' => $order_project['order_project_id'],
                    'commission_id' => $technician_info['commission_id'],
                    'money' => $money,
                    'type' => $cp['type'],
                    'value' => $cp['value']
                ];
            }
        }

    }

//    订单完成
    public function order_finish($order)
    {
        $projects = CashierOrderProjectModel::where([
            ['order_id', '=', $order->order_id],
        ])->select()->toArray();
        foreach ($projects as $k => $order_project) {
//            次卡/抢购核销
            $this->write_off($order_project);

//            员工提成
            $this->technicianMerits($order_project);
        }
        $model = new TechnicianMeritsModel();
        $model->saveAll($this->merits);
//        减库存
        $order_item = CashierOrderItemModel::where([
            ['order_id', '=', $order->order_id],
            ['shop_id', '=', $this->request->shopId]
        ])->field('goods_id,goods_sku_id,goods_num')->select()->toArray();
        foreach ($order_item as $item) {
            if ($item['goods_sku_id'] != 0) {
                $sku = GoodsSkuModel::find($item['goods_sku_id']);
                if ($sku != null) {
                    $sku->quota = $sku->quota - $item['goods_num'];
                    $sku->save();
                }
            }
            $good = GoodsModel::find($item['goods_id']);
            if ($good != null) {
                $good->quota = $good->quota - $item['goods_num'];
                $good->save();
            }
        }

    }

    public function orderCoupon($order)
    {
        $project_coupon = CashierOrderProjectModel::where([
            ['order_id', '=', $order->order_id],
            ['coupon_id', '<>', 0]
        ])->field('order_project_id,project_id,order_id,coupon_id')->select()->toArray();
        $good_coupon = CashierOrderItemModel::where([
            ['order_id', '=', $order->order_id],
            ['coupon_id', '<>', 0]
        ])->field('order_item_id,order_id,goods_id,coupon_id')->select()->toArray();
        return array_merge($good_coupon, $project_coupon);
    }

    public function pay()
    {
        $order_id = $this->request->param('order_id/d');
        $balance = $this->request->param('balance/s');
        if (empty($order_id)) {
            return $this->error('请选择要支付的订单');
        }
        if (null === $order = CashierOrderModel::find($order_id)) {
            return $this->error('订单不存在');
        }
        if ($order->status != 1 || $order->is_delete == 1) {
            return $this->error('订单不在未支付状态');
        }
        $member = MemberModel::find($order->member_id);
        if (!empty($balance)) {
            if ($order->member_id == 0) {
                return $this->error('游客不能使用余额支付#1');
            }
            if (null === $member) {
                return $this->error('游客不能使用余额支付#2');
            }
            if ($member->shop_id != $this->request->shopId) {
                return $this->error('游客不能使用余额支付#3');
            }
            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $member->member_id);
            if (!$MemberWalletLogic->checkBalance($balance)) return $this->error('会员余额不足');
        }


        $pay_type = $this->request->param('pay_type/d');
        $cash = $this->request->param('cash/s');
        $other_pay = bcsub(bcsub($order->need_pay, $balance, 2), $cash, 2);
        if ($other_pay != 0 && $pay_type == 0) {
            return $this->error('余额与现金支付金额不足');
        }

        $order->balance = $balance;
        $order->cash = $cash;
        $order->pay = $pay_type;
        if ($pay_type == 1 || $pay_type == 2) {
            if ($other_pay <= 0) return $this->error('移动支付金额不得小于0.01');
            $auth_code = $this->request->param('auth_code');
            $auth_code = str_replace(" ", "", $auth_code);
            $auth_code = trim($auth_code);
            if (empty($auth_code)) return $this->error('请输入条码信息');
            $out_trade_no = $this->build_order_no();
        }
        $response_return = '';
        switch ($pay_type) {
            case 0:
                Db::startTrans();
                try {
                    //优惠券处理
                    $coupon_list = $this->orderCoupon($order);
                    foreach ($coupon_list as $k => $v) {
                        if (null === $myCoupon = MemberCouponModel::find($v['coupon_id'])) {
                            Db::rollback();
                            return $this->error('优惠券不存在');
                        }
                        if ($myCoupon->status == 1) {
                            Db::rollback();
                            return $this->error('优惠券不存在');
                        }
                        $myCoupon->status = 1;
                        $myCoupon->save();
                        LogsLogic::coupon($this->request->shopId, $order->member_id, -1, 12, $v['coupon_id'], '', 0);
                    }

                    $needPay = round(($order->total_price * 100 - $order->coupon_money * 100 - $order->youhui_price * 100) / 100, 2);
                    dump($order->total_price);
                    dump($order->total_price);
                    if ($needPay <= 0) {
                        Db::rollback();
                        return $this->error('支付金额不正确');
                    }
                    if ($balance > 0) {
                        $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $member->member_id);
                        if ($needPay != 0) {
                            $res = $MemberWalletLogic->useBalance($balance, $order->total_price, 8); //商城购物使用
                            if ($res == false) {
                                Db::rollback();
                                return $this->error($MemberWalletLogic->getError());
                            }
                        }
                    }

                    $order->pay_time = time();
                    $order->status = 2; //订单的状态值
                    $order->save();

                    $this->usePrinter($order);

                    //最后处理，薪资提成、卡项核销
                    $this->order_finish($order);

                    //分销记录
                    $PartnerLogic = new PartnerLogic($order->shop_id);
                    $PartnerLogic->commission($order->member_id, $needPay);
                    Db::commit();
                    $response_return = '支付成功';
                } catch (\Exception $e) {
                    Db::rollback();
                    return $this->error($e->getMessage());
                }
                break;
            case 1:
                try {
                    $payment = new PaymentMicropayHelper($this->request->shopId);
                    $return = $payment->sendPayment([
                        'product_name' => '扫码支付',
                        'order_id' => $order_id,
                        'need_pay' => $other_pay,
                        'auth_code' => $auth_code,
                        'time_expire' => date("YmdHis", time() + 60),
                    ]);
                    if ($return['return_code'] === 'SUCCESS') {
                        //分销记录
                        $PartnerLogic = new PartnerLogic($order->shop_id);
                        $PartnerLogic->commission($order->member_id, $order->need_pay);
                        $order->pay_type = 'weixin';
                        $response_return = $return;
                    } else {
                        trace($order_id . '');
                        trace(json_encode($return));
                        return $this->error($return['return_msg']);
                    }
                } catch (\Exception $e) {
                    return $this->error($e->getMessage());
                }
                break;
            case 2:
                $payment = ShopAlPaymentModel::find($this->request->shopId);
                if ($payment == null) {
                    return $this->error('本商户未录入支付宝相关资料');
                }
                if ($order->out_trade_no != null) {
                    return $this->error('请勿重复下单');
                }
                $account = [
                    "appid" => $payment->appid,
                    "privateKey" => $payment->rsaPrivateKey,
                    "publicKey" => $payment->rsaPrivateKey,
                ];

                $alpay = new Alipay($account);
                $param = [
                    "out_trade_no" => $out_trade_no,
                    "total_amount" => $other_pay,
                    "subject" => '到店支付',
                    "auth_code" => $auth_code,
                    "scene" => "bar_code",//支付场景 条码支付，取值：bar_code 声波支付，取值：wave_code（必须）
                    "timeout_express" => "1m",//该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天
                ];
                $res = $alpay->facePay($param);
                $order->alpay_info = json_encode($res);
                $res['code'] = (int)$res['code'];
                if (in_array($res['code'], [10000, 10003])) {
                    $order->alpay_info = json_encode($res);
                    $order->pay_type = 'alpay';
                    $order->out_trade_no = $out_trade_no;
                    $order->save();
                } else {
                    return $this->error($res['sub_msg']);
                }
                $response_return = $res;
                break;

        }
        $order->save();
        return $this->success($response_return);
    }

    public function moneyPay()
    {
        $order_id = $this->request->param('order_id/d');
        if (empty($order_id)) {
            return $this->error('请选择要支付的订单');
        }
        if (null === $order = CashierOrderModel::find($order_id)) {
            return $this->error('订单不存在');
        }
        if ($order->status != 1 || $order->is_delete == 1) {
            return $this->error('订单不在未支付状态');
        }
        if ($order->member_id == 0) {
            return $this->error('游客不能使用余额支付#1');
        }
        if (null === $member = MemberModel::find($order->member_id)) {
            return $this->error('游客不能使用余额支付#2');
        }
        if ($member->shop_id != $this->request->shopId) {
            return $this->error('游客不能使用余额支付#3');
        }
        Db::startTrans();
        try {
//            优惠券处理
            $coupon_list = $this->orderCoupon($order);
            foreach ($coupon_list as $k => $v) {
                if (null === $myCoupon = MemberCouponModel::find($v['coupon_id'])) {
                    Db::rollback();
                    return $this->error('优惠券不存在');
                }
                if ($myCoupon->status == 1) {
                    Db::rollback();
                    return $this->error('优惠券不存在');
                }
                $myCoupon->status = 1;
                $myCoupon->save();
                LogsLogic::coupon($this->request->shopId, $order->member_id, -1, 12, $v['coupon_id'], '', 0);
            }

            $needPay = round(($order->total_price * 100 + -$order->coupon_money * 100 - $order->youhui_price * 100) / 100, 2);
            if ($needPay < 0) {
                Db::rollback();
                $this->error('支付金额不正确');
            }
            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $member->member_id);
            if ($needPay != 0) {
                $res = $MemberWalletLogic->useBalance($needPay, $order->total_price, 8); //商城购物使用
                if ($res == false) {
                    Db::rollback();
                    return $this->error($MemberWalletLogic->getError());
                }
            }
            $order->pay_time = time();
            $order->status = 2; //订单的状态值
            $order->pay_type = 'money';
            $order->save();

            $this->usePrinter($order);

//            最后处理，薪资提成、卡项核销
            $this->order_finish($order);


            //分销记录
//            $PartnerLogic = new PartnerLogic($order->shop_id);
//            $PartnerLogic->commission($order->member_id,$needPay);
//            return Db::rollback();
            Db::commit();
            return $this->success('余额支付成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    public function cashPay()
    {
        $order_id = $this->request->param('order_id/d');
        if (empty($order_id)) {
            return $this->error('请选择要支付的订单');
        }
        if (null === $order = CashierOrderModel::find($order_id)) {
            return $this->error('订单不存在');
        }
        if ($order->status != 1 || $order->is_delete == 1) {
            return $this->error('订单不在未支付状态');
        }
        if ($order->member_id != 0) {
            if (null === $member = MemberModel::find($order->member_id)) {
                return $this->error('会员不存在');
            }
            if ($member->shop_id != $this->request->shopId) {
                return $this->error('会员不存在');
            }
        }

        Db::startTrans();
        try {
//            优惠券处理
            $coupon_list = $this->orderCoupon($order);
            foreach ($coupon_list as $k => $v) {
                if (null === $myCoupon = MemberCouponModel::find($v['coupon_id'])) {
                    Db::rollback();
                    return $this->error('优惠券不存在');
                }
                if ($myCoupon->status == 1) {
                    Db::rollback();
                    return $this->error('优惠券不存在');
                }
                $myCoupon->status = 1;
                $myCoupon->save();
                LogsLogic::coupon($this->request->shopId, $order->member_id, -1, 12, $v['coupon_id'], '', 0);
            }

            $needPay = round(($order->total_price * 100 + -$order->coupon_money * 100 - $order->youhui_price * 100) / 100, 2);
            if ($needPay <= 0) {
                Db::rollback();
                $this->error('支付金额不正确');
            }
            $order->pay_time = time();
            $order->status = 2; //订单的状态值
            $order->pay_type = 'cash';
            $order->save();

            $this->usePrinter($order);

//            最后处理，薪资提成、卡项核销
            $this->order_finish($order);

            //分销记录
            $PartnerLogic = new PartnerLogic($order->shop_id);
            $PartnerLogic->commission($order->member_id, $needPay);

            Db::commit();
            return $this->success('现金支付成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    public function scanPay()
    {
        $auth_code = $this->request->param('auth_code');
        $order_id = $this->request->param('order_id');
        if (empty($order_id)) {
            return $this->error('请选择要支付的订单');
        }
        if (null === $order = CashierOrderModel::find($order_id)) {
            return $this->error('订单不存在');
        }
        if ($order->status != 1 || $order->is_delete == 1) {
            return $this->error('订单不在未支付状态');
        }
        if ((float)$order->need_pay <= 0) {
            return $this->error('订单支付金额不得小于0');
        }

        $order->pay_type = 'weixin';
        $order->save();
        try {
            $payment = new PaymentMicropayHelper($this->request->shopId);
            $return = $payment->sendPayment([
                'product_name' => '扫码支付',
                'order_id' => $order_id,
                'need_pay' => $order->need_pay,
                'auth_code' => $auth_code,
            ]);
            if ($return['return_code'] === 'SUCCESS') {
//            if($return['result_code'] === 'SUCCESS'){
//
//            }else{
//                return $this->error($return['err_code_des']);
//            }
                //分销记录
                $PartnerLogic = new PartnerLogic($order->shop_id);
                $PartnerLogic->commission($order->member_id, $order->need_pay);
                return $this->success($return);
            }
            return $this->error($return['return_msg']);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    public function alPay()
    {
        $auth_code = $this->request->param('auth_code');
        $auth_code = str_replace(" ", "", $auth_code);
        $auth_code = trim($auth_code);
        $order_id = $this->request->param('order_id');
        if (empty($order_id)) {
            return $this->error('请选择要支付的订单');
        }
        if (null === $order = CashierOrderModel::find($order_id)) {
            return $this->error('订单不存在');
        }
        if ($order->status != 1 || $order->is_delete == 1) {
            return $this->error('订单不在未支付状态');
        }
        if ((float)$order->need_pay <= 0) {
            return $this->error('订单支付金额不得小于0');
        }
        $payment = ShopAlPaymentModel::find($this->request->shopId);
        if ($payment == null) {
            return $this->error('本商户未录入支付宝相关资料');
        }
        if ($order->out_trade_no != null) {
            return $this->error('请勿重复下单');
        }
        $out_trade_no = $this->build_order_no();
        $account = [
            "appid" => $payment->appid,
            "privateKey" => $payment->rsaPrivateKey,
            "publicKey" => $payment->rsaPrivateKey,
        ];

        $alpay = new Alipay($account);
        $param = [
            "out_trade_no" => $out_trade_no,
            "total_amount" => $order->need_pay,
            "subject" => '到店支付',
            "auth_code" => $auth_code,
            "scene" => "bar_code",//支付场景 条码支付，取值：bar_code 声波支付，取值：wave_code（必须）
            "timeout_express" => "2m",//该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天
        ];
        $res = $alpay->facePay($param);
        $order->alpay_info = json_encode($res);
        $order->save();
        $res['code'] = (int)$res['code'];
        if (in_array($res['code'], [10000, 10003])) {
            $order->alpay_info = json_encode($res);
            $order->pay_type = 'alpay';
            $order->out_trade_no = $out_trade_no;
            $order->save();
            return $this->success();
        }
        return $this->error($res);


//        $barPayRequestBuilder = new \AlipayTradePayContentBuilder();
//        $barPayRequestBuilder->setOutTradeNo($outTradeNo);
//        $barPayRequestBuilder->setTotalAmount($totalAmount);
//        $barPayRequestBuilder->setAuthCode($authCode);


    }

    public function build_order_no()
    {
        return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }

    public function queryOrder()
    {
//        $cert = <<<EOT
//-----BEGIN CERTIFICATE-----
//MIIEJDCCAwygAwIBAgIUec4uhcQXnjPolR3hmu84pjMeMqQwDQYJKoZIhvcNAQEL
//BQAwXjELMAkGA1UEBhMCQ04xEzARBgNVBAoTClRlbnBheS5jb20xHTAbBgNVBAsT
//FFRlbnBheS5jb20gQ0EgQ2VudGVyMRswGQYDVQQDExJUZW5wYXkuY29tIFJvb3Qg
//Q0EwHhcNMjQwMTIyMTQ0OTIyWhcNMjkwMTIwMTQ0OTIyWjB+MRMwEQYDVQQDDAox
//NDk1MzM3NTQyMRswGQYDVQQKDBLlvq7kv6HllYbmiLfns7vnu58xKjAoBgNVBAsM
//Iee7temYs+W4gua2quWfjuWMuuW9kuadpei9sOi2tOmmhjELMAkGA1UEBhMCQ04x
//ETAPBgNVBAcMCFNoZW5aaGVuMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC
//AQEA3BEsRH9CSNY3Oz2w3Vv8RFfblk/UHfFtEWEbN1texuxXMcyNsUStVkyU3hEg
//dnurlqHGVbU7GQVMjN7uqLjIkd0k6dDBrOcs/JY9dU7UV9KIy/CV6I96WsVzavie
//wgN6JhummlTELnGy4pvBlVFrPC9OI/eZyt7kHDvGwRJkrKv0+C5qnTaRCEeFvuUE
//Ysx7g554ECgyg/jIhkuuLZkSd+ocwfGy9dvnKAczlv0hVqCHCTF6Xo4ewEMM4tEQ
//Xi3dsDXKDyljrvBhxJws45TTTs6sYlWpth4aDUMkjroJBMawrGa2wWQOtHbLjijc
//5QtIyvR9414cMNvEVeWJ6Qnw9wIDAQABo4G5MIG2MAkGA1UdEwQCMAAwCwYDVR0P
//BAQDAgP4MIGbBgNVHR8EgZMwgZAwgY2ggYqggYeGgYRodHRwOi8vZXZjYS5pdHJ1
//cy5jb20uY24vcHVibGljL2l0cnVzY3JsP0NBPTFCRDQyMjBFNTBEQkMwNEIwNkFE
//Mzk3NTQ5ODQ2QzAxQzNFOEVCRDImc2c9SEFDQzQ3MUI2NTQyMkUxMkIyN0E5RDMz
//QTg3QUQxQ0RGNTkyNkUxNDAzNzEwDQYJKoZIhvcNAQELBQADggEBAIkHAeql40IC
//I0YVw9D0SqnezilyrdIP2ZJxTzJZJSPvZE/BXDNmOFwyHny8vv2wKG8y1LcHTrAF
//vrHxDKRcMvhbikf7N2a4RvzBnRgeTuMejsd5jwXjbtd9wFMFkr1vqas27yGp+OtJ
//+T9OvmQ6Jsb+qxUCV13RjPtpUN0J+KB8bxaCgsImh+GpMC0cfCtwiX9UQzeYP6JA
//braTcJr64moumFNvuHDZdySMCShfBV1ETz36CDF5vY50VV5oefh1EqeUcBuJ0zp0
//iucm9wMtNcwyFCDvajqYZyP1GL5hYEeTFZU4zZLqhOKfpSFRsNsQ4eiEboeEwml/
//KanAd8fStDs=
//-----END CERTIFICATE-----
//EOT;
//
//        dump(md5($cert).'_cert.perm');
//        $key = <<<EOT
//-----BEGIN PRIVATE KEY-----
//MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDcESxEf0JI1jc7
//PbDdW/xEV9uWT9Qd8W0RYRs3W17G7FcxzI2xRK1WTJTeESB2e6uWocZVtTsZBUyM
//3u6ouMiR3STp0MGs5yz8lj11TtRX0ojL8JXoj3paxXNq+J7CA3omG6aaVMQucbLi
//m8GVUWs8L04j95nK3uQcO8bBEmSsq/T4LmqdNpEIR4W+5QRizHuDnngQKDKD+MiG
//S64tmRJ36hzB8bL12+coBzOW/SFWoIcJMXpejh7AQwzi0RBeLd2wNcoPKWOu8GHE
//nCzjlNNOzqxiVam2HhoNQySOugkExrCsZrbBZA60dsuOKNzlC0jK9H3jXhww28RV
//5YnpCfD3AgMBAAECggEBAIBmTKvSjHwu8J7SCcW+C9xcXrS+8wZdfMOtItITr6Lk
//9qMJtIp/hZtap2lCGOzIj38d+Li9OzQIEXgIArvSxMPGgekicj5Ny8O8bTNqwR5U
//qphDUVQVktAvcH4zfX25xaVCcNyPJL/sevEY68QRcz30Y+U8bDEgB3wprHeuIatU
//vESL9i2EdEfCECuLcVH6Gjz5oVqXMGsjZMrhcmoJDQV1VZWIkL23h7lJI2QUJgeV
//x8FNvgZe13iWvGWV6k4QHj0nUCFS80X/C0bvYInc3hxXMdR6sKLH3ugkcKXYN8eh
//ArTVHXopBoPmIoVWBfAfXLIvfqUaSmMPP+hL/xiYmiECgYEA9SoOEJVJQVDVziE2
//eDs7XIoRNSvU0aGEtlhjXxIgLliRFY/nXEiwiTEmmfDsY8Fref/hsOmye1gszs0e
//zlUS8c0SFGI2+/WaOQfMxqhNUbzt/gK/sJdBYtgq3gjCQuOFuj0/DVdWS58Al9gz
//lBWztP4MgilRm7rrPivgcxXsyP8CgYEA5csm/PmmMwwsNg8ED/6f6lGeFxDGuZp1
//JIWD9P9Nuoe+7ln+nuLHymqc+iCqajFcUHXTfmRzGuNFmIEKWa6glwp0e1vPjCa+
//H2DRVLx0dLiNV30v72qeTssh1J07y/gI22a1B4lDFtS7IUbKzamq9rNe2kL3hftN
//+oLm8+ZpIAkCgYEAmxeOrDj0jahIiU0De03lQKZrOlrPGAp4vS3vNy5tQ0RuC9js
//QLoPS8rXI52AvZ6XkicorFU6vsLKHc0vRtIU2PilDlYPeJcniBqCFc5Uk3fUitNM
//Vrdo+tHLVIjv84ahi27BW3w7sD0XD/gKsQyFkeMBILpo0P6PYNY6+DMPhxsCgYAh
//RmOk6jmo1rBoO5BpCIP7mEn+KQ29vqIL4dGT3oxQ4GtDdICsXUZ1By8oASbsLa2i
//cQ1pFf6c/CANz1HCXskeVgM8AbVyJAIP5SMq1AdBB6Bf9N7GGnhGDKAfe403IfmW
//W68HIlc2rSNT1D51vYXmJ18q19uj6RoHloD+/HRokQKBgQCBl+9j7xetnpAiftEq
//CBPc/q8eMLFRz5haKFh6wKwmtqt6e6DZtUB2qS6TLD63Cz7plQr+F6jZ7cozm7ke
//2FcPP9OuUuBGLuxDYTjHhyEvxURuoQj85isZlXe+YHJ8BjYkkkfTMjRlHBa5vubu
//WnqsKukQI1zRfgfKZkgYwLfPzA==
//-----END PRIVATE KEY-----
//EOT;
//
//        dd(md5($key).'_key.perm');
        $order_id = $this->request->param('order_id');
        if (empty($order_id)) {
            return $this->error('请选择要支付的订单');
        }
        if (null === $order = CashierOrderModel::find($order_id)) {
            return $this->error('订单不存在');
        }
        if ($order->is_delete == 1) {
            return $this->error('订单不在未支付状态');
        }
        if ($order->status == 2) {
            return $this->success('订单已完成');
        }
        if ($order->pay != 1 && $order->pay != 2) {
            return $this->error('订单无需查询支付状态');
        }


        try {
            if ($order->pay == 1) {
                $payment = new PaymentMicropayHelper($this->request->shopId);
                $return = $payment->queryOrder($order_id);
                if ($return['return_code'] === 'SUCCESS') {
                    if ($return['result_code'] === 'SUCCESS') {
                        if ($return['trade_state'] === 'SUCCESS') {
                            if ($order->pay_time == 0) {
                                $order->pay_time = time();
                                $order->pay_type = 'weixin';
                                $order->status = 2;
                                $order->save();
                                //            最后处理，薪资提成、卡项核销
                                $this->order_finish($order);
                                //              优惠券处理
                                $coupon_list = $this->orderCoupon($order);
                                foreach ($coupon_list as $k => $v) {
                                    if (null === $myCoupon = MemberCouponModel::find($v['coupon_id'])) {
                                        continue;
                                    }
                                    if ($myCoupon->status == 1) {
                                        continue;
                                    }
                                    $myCoupon->status = 1;
                                    $myCoupon->save();
                                    LogsLogic::coupon($this->request->shopId, $order->member_id, -1, 12, $v['coupon_id'], '', 0);
                                }
                                $this->use_balance($order->balance, $order->total_price, $order->member_id);
                                $this->usePrinter($order);
                            }
                        }
                    }
                    return $this->success($return);
                }
                return $this->error($return['return_msg']);
            } else if ($order->pay == 2) {
                if ($order->out_trade_no == null) {
                    return $this->error("订单未发起支付");
                }
                $payment = ShopAlPaymentModel::find($this->request->shopId);
                if ($payment == null) {
                    return $this->error('本商户未录入支付宝相关资料');
                }
                $account = [
                    "appid" => $payment->appid,
                    "privateKey" => $payment->rsaPrivateKey,
                    "publicKey" => $payment->rsaPrivateKey,
                ];
                $data = [
                    "out_trade_no" => $order->out_trade_no,
                    'trade_no' => ''
                ];
                $alpay = new Alipay($account);
                $res = $alpay->orderquery($data);
                if (!$res['code'] == 10000) return $this->error('订单查询失败');


                if ($res['trade_status'] == 'TRADE_CLOSED') return $this->success(401);
                if ($res['trade_status'] == 'WAIT_BUYER_PAY') return $this->success(301);
                $order->alpay_info = json_encode($res);
                if ($order->pay_time == 0) {
                    $order->pay_time = time();
                    $order->status = 2;
                    $order->save();
                    //            最后处理，薪资提成、卡项核销
                    $this->order_finish($order);
                    //              优惠券处理
                    $coupon_list = $this->orderCoupon($order);
                    foreach ($coupon_list as $k => $v) {
                        if (null === $myCoupon = MemberCouponModel::find($v['coupon_id'])) {
                            continue;
                        }
                        if ($myCoupon->status == 1) {
                            continue;
                        }
                        $myCoupon->status = 1;
                        $myCoupon->save();
                        LogsLogic::coupon($this->request->shopId, $order->member_id, -1, 12, $v['coupon_id'], '', 0);
                    }

                    $this->use_balance($order->balance, $order->total_price, $order->member_id);

                    $this->usePrinter($order);

                } else {
                    $order->save();
                }
                if ($res['trade_status'] == 'TRADE_SUCCESS') return $this->success(200);
                if ($res['trade_status'] == 'TRADE_FINISHED') return $this->success(201);
                return $this->error('未知错误');

            }
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    public function use_balance($balance, $total_price, $member)
    {
        if ($balance == 0) return;
        if (is_numeric($member)) {
            $member = MemberModel::find($member);
        }
        if ($member == null) return $this->error('会员不存在');
        if ($member->shop_id != $this->request->shopId) return $this->error('会员不存在');
        $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $member->member_id);
        $res = $MemberWalletLogic->useBalance($balance, $total_price, 8); //商城购物使用

    }

    public function cancelPay()
    {
        $order_id = $this->request->param('order_id');
        if (empty($order_id)) {
            return $this->success('成功');
        }
        if (null === $order = CashierOrderModel::find($order_id)) {
            return $this->success('成功');
        }
        if ($order->status != 1 || $order->is_delete == 1) {
            return $this->success('成功');
        }

        $payment = new PaymentMicropayHelper($this->request->shopId);
        $return = $payment->cancelPay($order_id);

        $order->status = -1;
        $order->save();
        return $this->success('成功');

    }

    public function cancelOrder()
    {
        $order_id = $this->request->param('order_id');
        if (empty($order_id)) {
            return $this->error('请选择要支付的订单');
        }
        if (null === $order = CashierOrderModel::find($order_id)) {
            return $this->error('订单不存在');
        }
        if ($order->status != 1 || $order->is_delete == 1) {
            return $this->error('订单不在未支付状态');
        }

        $order->status = -1;
        $order->save();
        return $this->success('成功');
    }

    protected function usePrinter($order)
    {
        //打印机
        $printer_logic = new PrinterLogic($this->request->shopId);
        $printer_logic->print('cashOrder', $order->order_id);
    }
}
